package cn.com.web.filter;

import cn.com.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "AutoLoginFilter",urlPatterns = "*.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //设置中文
        response.setContentType("text/html; charset=UTF-8");
        HttpSession session = request.getSession();
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        //如果访问的是以下jsp则放行
        if (servletPath.equals("/showfoundcustomer.jsp") || servletPath.equals("/LoginServlet")
            ||servletPath.equals("/roomviewa.jsp") || servletPath.equals("/login.jsp")
             ||servletPath.equals("/roomDetailsa.jsp") || servletPath.equals("/index.jsp") )
        {
            chain.doFilter(req, resp);
            return;
        }
        PrintWriter out = response.getWriter();
        Object aa = session.getAttribute("user");
        if (aa!=null) {
            // user存在时放行
            chain.doFilter(req, resp);
        }
        else {
            //查看是否自动登录
            Cookie[] cookies=request.getCookies();
            if (cookies!=null){
                for (Cookie cookie : cookies) {
                    if (cookie!=null){
                        if (cookie.getName().equals("autologin"))
                        {
                            String value = cookie.getValue();
                            String[] split = value.split("-");
                            String username=split[0];
                            String password=split[1];
                            User user=new User(username,password);
                            session.setAttribute("user",user);
                            chain.doFilter(req, resp);
                            return;
                        }
                    }
                }
            }

            req.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
